import java.io.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.time.temporal.ChronoUnit;
public class Sale implements Serializable {
    private static final long serialVersionUID = 1L;
    private double money;
    public static  List<Ticket> tickets = new ArrayList<>();
    public static void saveStaticData(String filePath) throws IOException {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath))) {
            oos.writeObject(tickets);
            System.out.println("电子票数据已保存到: " + filePath);
        } catch (IOException e) {
            System.out.println("电子票数据失败: " + e.getMessage());
            throw e;
        }
    }

    // 从文件加载静态数据（电影和场次）
    @SuppressWarnings("unchecked")
    public static void loadStaticData(String filePath) throws IOException, ClassNotFoundException {
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("电影/场次数据文件不存在，将使用空列表");
            return;
        }

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath))) {
            tickets = (ArrayList<Ticket>) ois.readObject();
            System.out.println("已加载"+ tickets.size()+" 张电子票");
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("加载电子票数据失败: " + e.getMessage());
            throw e;
        }
    }

    public Session searchSession(Film film, LocalDateTime startTime, Screenroom screenroom) {
        if (film == null || startTime == null || screenroom == null) {
            System.out.println("查找失败：电影、时间或影厅信息不能为空");
            return null;
        }
        LocalDateTime inputTimeTruncated = startTime.truncatedTo(ChronoUnit.MINUTES);
        for (Session session : Plan.sessions) {
            boolean filmMatch = session.getFilm().trim().equalsIgnoreCase(film.getTitle().trim());
            LocalDateTime sessionTimeTruncated = session.getStartTime().truncatedTo(ChronoUnit.MINUTES);
            boolean timeMatch = sessionTimeTruncated.equals(inputTimeTruncated);
            boolean roomMatch = session.getScreen().getRoomName().equals(screenroom.getRoomName());
            if (filmMatch && timeMatch && roomMatch) {
                return session;
            }
        }
        System.out.println("未找到匹配的场次（已忽略秒和毫秒差异）");
        return null;
    }

    public void chooseChair(Session session,int row,int col,int x){//row行，col列
        for(int i=0;i<x;i++){
            if(!session.getSeat(row,col+i)){
                session.setSeat(row,col+i,true);
                session.setQA(true);
                session.setTicketNum(x,true);
                Ticket ticket = new Ticket(
                        session.getFilm(),
                        session.getScreenRoom(),
                        session.getStartTime(),
                        row,
                        col + i,
                        session.getCurrentMoney()
                );
                tickets.add(ticket);
                System.out.println("售票成功！电子票信息:\n" + ticket.getTicketInfo());
            }
            else {
                System.out.println("该座位有人");
            }}
    }
    public boolean findPeople(Session session){
        for(int i = 0;i<session.getScreen().column;i++){
            for(int j = 0;j<session.getScreen().row;j++){
                if(session.getSeat(i, j)){
                    return true;
                }
            }
        }
        return false;
    }
    public void deleteChair(Session session, int row, int col) {
        if (session.getSeat(row, col)) {
            session.setSeat(row, col, false);
            session.setQA(findPeople(session));
            session.setTicketNum(0, false);
            session.setReTicket();

            Iterator<Ticket> iterator = tickets.iterator();
            boolean ticketFound = false;

            while (iterator.hasNext()) {
                Ticket ticket = iterator.next();
                if (ticket.getRow() == row && ticket.getColumn() == col &&
                        ticket.isActive() &&
                        ticket.getFilmTitle().equals(session.getFilm())) {

                    ticket.invalidate();
                    iterator.remove();
                    System.out.println("退票成功！电子票已失效:\n" + ticket.getTicketInfo());
                    ticketFound = true;
                    break;
                }
            }

            if (!ticketFound) {
                System.out.println("未找到对应的有效电子票");
            }
        } else {
            System.out.println("该座位没人");
        }
    }
    public Ticket findTicket(String ticketId) {
        for (Ticket ticket : tickets) {
            if (ticket.getTicketId().equals(ticketId)) {
                return ticket;
            }
        }
        return null;
    }
    public double getMoney() {
        return money;
    }

    public void setMoney(double money,boolean bl) {
        if(bl){
            this.money+=money;
        }
        else {
            this.money-=money;
        }
    }
}
